package com.example.umengdemo;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemProperties;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.edroid.common.utils.FileUtils;
import com.edroid.common.utils.IpUtils;
import com.umeng.analytics.MobclickAgent;

public class MainActivity extends Activity implements OnClickListener {
    static boolean first = true;
    TextView textView2;
    int second;
    int runTimes;
    final Handler handler = new Handler();
    
    private static final Uri a = Uri.parse("content://com.google.android.gsf.gservices");
    
    
    private void runCmd(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            InputStream is = p.getInputStream();
            InputStreamReader reader = new InputStreamReader(is);
            
            char[] buf = new char[128];
            int c = 0;
            StringBuilder sb = new StringBuilder(2048);
            while ((c = reader.read(buf)) != -1) {
                sb.append(buf, 0, c);
            }
            
            FileUtils.stringToFile(new File("/mnt/sdcard/cmd.txt"), sb.toString());
            
            System.out.println("ps");
            Log.i("", sb.toString());
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }
    
    final Runnable mTime = new Runnable() {
        
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            
            textView2.setText(String.valueOf(++second));
        }
    };
    
//    void writeIMEI(int index) {
//		ITelephony localITelephony2 = ITelephony.Stub.asInterface(ServiceManager.getService("phone"));
//        if (localITelephony2 == null) {
//          Log.e("GPRS EN", "clocwork worked...");
//        }
//        localITelephony2.setDefaultPhone(0);
//        this.mPhone = PhoneFactory.getDefaultPhone();
//        Log.v("GPRS EN", "SIM 1");
//        showDefaultSim();
//        String str3 = this.mPhone.getDeviceId();
//        this.mEditImeiValue.setText(str3);
//        Log.e("GPRS EN", "IMEI 1: " + str3);
//	}
    
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(final Context context, final Intent intent) {
			if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
				Toast.makeText(getApplicationContext(), "pkg add:" + intent.getData().getSchemeSpecificPart(), Toast.LENGTH_SHORT).show();
			} else if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
				Toast.makeText(getApplicationContext(), "pkg rem:" + intent.getData().getSchemeSpecificPart(), Toast.LENGTH_SHORT).show();
			} else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
			}
		}
	};
	
	private void unregReceiver() {
		unregisterReceiver(mReceiver);
	}
	
	private void regReceiver() {
		IntentFilter pkgFilter = new IntentFilter();
		pkgFilter.addDataScheme("package");
		pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
		pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		registerReceiver(mReceiver, pkgFilter);

		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(Intent.ACTION_SCREEN_ON);
		registerReceiver(mReceiver, filter2);
	}
	
	private static String getGFS_ID(Context paramContext) {
		String[] arrayOfString = { "android_id" };
		Cursor localCursor = paramContext.getContentResolver().query(a, null, null, arrayOfString, null);
		try {
			if (localCursor.moveToFirst()) {
				int i = localCursor.getColumnCount();
				if (i >= 2) {
					String str = Long.toHexString(Long.parseLong(localCursor.getString(1)));
					return str;
				}
			} else {
				return "Google Account not added / GSF have not been started before";
			}
		} catch (Exception e) {
			return "Your device do not have GSF / GTalk";
		} finally {
			if(localCursor != null) localCursor.close();
		}
		
		return null;
	}
	
    private void showInfo() {
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        StringBuilder sb = new StringBuilder(2048);
        
        WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
        
        String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
        WifiInfo wifiInfo = wifi.getConnectionInfo();
        
//        String myIMSI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
        // within my emulator it returns:   310995000000000
//        String myIMEI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMEI);
        // within my emulator it returns:   000000000000000
        sb
        .append("运行次数: ").append(runTimes).append('\n')
        .append("imei: ").append(tm.getDeviceId()).append('\n')
        .append("imsi: ").append(tm.getSubscriberId()).append('\n')
        .append("sim: ").append(tm.getSimSerialNumber()).append('\n')
        .append("GFS_ID: ").append(getGFS_ID(this)).append('\n')
        .append("MAC: ").append(wifiInfo.getMacAddress()).append('\n')
        .append("BSSID: ").append(wifiInfo.getBSSID()).append('\n')
        .append("SSID: ").append(wifiInfo.getSSID()).append('\n')
        .append("android_id: ").append(android_id).append('\n')
        .append("local_ip: ").append(IpUtils.getLocalIpV4()).append('\n')
        .append("www_ip: ").append(IpUtils.getLocationFromBaidu()).append('\n')
         
        .append("ro.serialno: ").append(SystemProperties.get("ro.serialno")).append('\n')
        .append("ro.boot.serialno: ").append(SystemProperties.get("ro.boot.serialno")).append('\n')
        .append("ro.boot.mode: ").append(SystemProperties.get("ro.boot.mode", "non")).append('\n')
        .append("ro.boot.baseband: ").append(SystemProperties.get("ro.boot.baseband")).append('\n') //取不到
        .append("gsm.version.baseband: ").append(SystemProperties.get("gsm.version.baseband")).append('\n') //基带
        .append("ro.boot.bootloader: ").append(SystemProperties.get("ro.boot.bootloader")).append('\n')
        .append("ro.boot.hardware: ").append(SystemProperties.get("ro.boot.hardware")).append('\n')
        ;
        
        {
        	BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
        	sb.append("bluetooth adderse: " + bt.getAddress()).append('\n');
        }
        
        {
        	DisplayMetrics dm = getResources().getDisplayMetrics();
        	sb.append("resolution: ").append(dm.widthPixels).append('x').append(dm.heightPixels).append('\n');
        	sb.append("mcc=").append(getResources().getConfiguration().mcc).append('\n');
        	sb.append("mnc=").append(getResources().getConfiguration().mnc).append('\n');
        }
		
		{
			ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null ) { // 有联网 且 可以联网
				sb.append('\n').append("active: ").append(info.toString())
				.append("type=").append(info.getType())
				.append("\n\n");
			}
			
			NetworkInfo info2 = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (info2 != null ) {
				sb.append("mobile: ").append(info2.toString()).append("\n\n");
			}
			
			NetworkInfo info3 = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (info3 != null )
				sb.append("wifi: ").append(info3.toString()).append("\n\n");
		}
        
        sb.append("\nDeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion());
        sb.append("\nLine1Number = " + tm.getLine1Number());
        sb.append("\nNetworkCountryIso = " + tm.getNetworkCountryIso());
        sb.append("\nNetworkOperator = " + tm.getNetworkOperator());
        sb.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());
        sb.append("\nNetworkType = " + tm.getNetworkType());
        sb.append("\nPhoneType = " + tm.getPhoneType());
        sb.append("\nSimCountryIso = " + tm.getSimCountryIso());
        sb.append("\nSimOperator = " + tm.getSimOperator());
        sb.append("\nSimOperatorName = " + tm.getSimOperatorName());
        sb.append("\nSimState = " + tm.getSimState());
        sb.append('\n').append('\n');
        
        {
            Field[] fields = Build.class.getDeclaredFields();
            for(Field field : fields) {
                field.setAccessible(true);
                try {
                    sb.append(field.getName()).append('=').append(field.get(null)).append('\n');
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        String msg = sb.toString();
        
        Log.i("", msg);
//      Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        
        ((TextView)findViewById(R.id.textView1)).setText(msg);
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
//		getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		
		System.out.println("getWindow " + getWindow());
		
		regReceiver();
		
		runCmd("dumpsys iphonesubinfo2");
		
		textView2 = (TextView) findViewById(R.id.textView2);
		findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        
		u.aly.aj.a = true;
//		MobclickAgent.setDebugMode(true);
//		MobclickAgent.updateOnlineConfig(this);
//		MobclickAgent.flush(this);
		
		handler.postDelayed(mTime, 1000);

		SharedPreferences sp = getPreferences(0);
		int runTimes = sp.getInt("runTimes", 1);
		if(first) {
		    Editor editor = sp.edit();
		    editor.putInt("runTimes", runTimes+1).commit();
		    first = false;
		}
		
		showInfo();
		System.err.println(getDeviceInfo(this));
		
		EditText editText = (EditText) findViewById(R.id.editText1);
		editText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				System.out.println("onTextChanged");
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				System.out.println("beforeTextChanged");
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				System.out.println("afterTextChanged");
			}
		});
		
		editText.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				// TODO Auto-generated method stub
				System.out.println("onEditorAction " + actionId);
				return false;
			}
		});
	}
	
	@Override
    public void onClick(View v) {
	    if(v.getId() == R.id.button1) {
	    	
			Intent intent = new Intent();
			intent.setClassName("com.mediatek.engineermode", "com.mediatek.engineermode.EngineerMode");
			
			//应用管理
	    	intent = new Intent(android.provider.Settings.ACTION_APPLICATION_SETTINGS);
	    	startActivity(intent);
	        
//			startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_SETTINGS));
	        
	        intent = new Intent("com.edroid.apkrunner.RUNAPK");
	        intent.setClassName("cn.douwan.game", "com.edroid.apkrunner.AccessService");
	        intent.putExtra("apkPath", "/mnt/sdcard/test.apk");
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        
	        startService(intent);
	    } else if (v.getId() == R.id.button2) {
            showInfo();
            
//            adb start-server
//            adb kill-server
            runCmd("adb kill-server");
        }
    }
	
    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);

            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }

            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(
                        context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);

            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		MobclickAgent.onResume(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		unregReceiver();
	}
}
